// showHtml project main.go
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"time"

	. "github.com/soekchl/myUtils"
)

type TEMP struct {
	imageStr string
}

type OutFileInfo struct {
	fileName string
	info     string
	titleAdd string
}

var (
	allImagesList []TEMP
	pageCount     = 50
)

func main() {
	if len(os.Args) == 3 {
		pageCount, _ = strconv.Atoi(os.Args[2])
		if pageCount < 1 {
			pageCount = 100
		}
	}
	Notice("PageCount = ", pageCount)

	dir, err := ioutil.ReadDir("./")
	if err != nil {
		Error(err)
		return
	}

	allImagesList = make([]TEMP, len(dir)+10)

	i := 1 // 偏差值
	if len(dir) > 0 {
		i = getStrInt(dir[0].Name())
	}
	for _, v := range dir {
		if v.IsDir() {
			allImagesList[getStrInt(v.Name())-i].imageStr = createHtml(v.Name())
		}
	}

	n := 0
	m := 0

	var ofm []*OutFileInfo

	var navigationBar []string
	imagesStr := ""

	for _, v := range allImagesList {
		if len(v.imageStr) < 1 {
			continue
		}
		imagesStr += v.imageStr
		m++

		if m%pageCount == 0 {
			navigationBar = append(navigationBar, changeNavigation(getTitle(), n+1, n*pageCount+1, n*pageCount+m))
			ofm = append(ofm, &OutFileInfo{
				fileName: fmt.Sprintf("comic_%d.html", n+1),
				info:     imagesStr,
				titleAdd: fmt.Sprintf(" %v-%v ", n*pageCount+1, n*pageCount+m),
			})
			n++
			imagesStr = ""
			m = 0
		}
	}

	if m != 0 { // NOTE check need add one
		navigationBar = append(navigationBar, changeNavigation(getTitle(), n+1, n*pageCount+1, n*pageCount+m))
		ofm = append(ofm, &OutFileInfo{
			fileName: fmt.Sprintf("comic_%d.html", n+1),
			info:     imagesStr,
			titleAdd: fmt.Sprintf(" %v-%v ", n*pageCount+1, n*pageCount+m),
		})
	}

	f := func(kk int, isHead bool) string {
		str := ""
		tmpBar := ""
		for k, v := range navigationBar {
			if kk-1 == k || kk+1 == k {
				tmpBar += v
				if kk-1 == k {
					tmpBar += "---"
				}
			}

			if kk == k {
				str += "<span> ... </span>"
			} else {
				str += v
			}
		}
		tmpBar = fmt.Sprintf("<br><H3>%s</H3><br>", tmpBar)
		if isHead {
			return tmpBar + str
		}
		return str + tmpBar
	}

	for k, v := range ofm { // 统一输出
		head := f(k, false)
		tail := f(k, true)
		outFile(v.fileName, v.titleAdd, head+v.info+tail)
	}
}

func createHtml(fileName string) (outFileStr string) {
	defer func() {
		if err := recover(); err != nil {
			Error(fileName, " Err=", err)
			time.Sleep(time.Second * 3)
		}
	}()
	dir, err := ioutil.ReadDir(fileName)
	if err != nil {
		Error(err)
		return
	}

	images_str := make([]string, len(dir)+10)

	i := 1 // 偏差值
	if len(dir) > 0 {
		i = getStrInt(dir[0].Name())
	}

	for _, v := range dir {
		images_str[getStrInt(v.Name())-i] = fmt.Sprintf(imgModel, "./"+fileName+"/"+v.Name(), time.Now().Unix(), fileName)
	}

	outFileStr = strings.Join(images_str, "")

	return
}

func getStrInt(name string) (dest int) {
	f := true
	for i, _ := range name {
		if name[i] >= 48 && name[i] <= 57 {
			dest *= 10
			dest += charToInt(name[i])
			f = false
		} else if f {
			continue
		} else {
			break
		}
	}
	return dest
}

func charToInt(c byte) int {
	return int(c - 48)
}

func outFile(fileName, titleAdd, outFileStr string) {
	outFileStr = fmt.Sprintf(htmlModel, getTitle()+titleAdd, htmlStyle, outFileStr)
	fi, err := os.Create(fileName)
	if err != nil {
		Error(err)
		return
	}
	fi.WriteString(outFileStr)
	fi.Close()
}

func getTitle() (title string) {
	if len(os.Args) > 1 {
		title = os.Args[1]
	}
	return
}

func changeNavigation(title string, words, start, stop int) string {
	if start == stop {
		return fmt.Sprintf(`<a href="/%s/comic_%d.html">[%v]</a>`, title, words, stop)
	}
	return fmt.Sprintf(`<a href="/%s/comic_%d.html">[%v-%v]</a>`, title, words, start, stop)
}
